import './index.scss'

import { Card, List, Progress, Radio, Typography } from 'antd'
import { CaretDownOutlined, CaretUpOutlined } from '@ant-design/icons'
import React, { useEffect, useState } from 'react'
import { changePieData, pieDataInterFace } from '@/store/modules/echarts'
import { useBrand, useOrders } from '@/api/query'

import Echarts from '@/components/Echarts'
import HomeIntro from '@/components/HomeIntro'
import { Orderlist } from '@/types/order/order'
import PubSub from 'pubsub-js'
import { getPieData } from './hooks/usePieData'
import { useAppDispatch } from '@/store/hooks'
import { useEchartsData } from './EchartsData'

const App: React.FC = () => {
  const { isError, isLoading, data } = useBrand(1, 10, '')
  const {
    isError: isError2,
    isLoading: isLoading2,
    data: orderList
  } = useOrders()
  const [listData, setListData] = useState<string[]>([])
  const [defaultPieData, setDefaultPieData] = useState<pieDataInterFace[]>([])
  const [showIntro, setshowIntro] = useState<boolean>(false)
  const [showStatus, setShowStatus] = useState<string>('all')
  const [payDate, setPayDate] = useState<string[]>([])
  const [payCount, setPayCount] = useState<number[]>([])
  // 定义总销售额
  const [totalSales, setTotalSales] = useState<number>(0)
  const dispatch = useAppDispatch()

  useEffect(() => {
    // 是否显示引导页
    const flag = localStorage.getItem('showIntro') || ''
    setshowIntro(flag === 'true' ? true : false)

    // 订阅消息
    PubSub.subscribe('setData', (msg, data) => {
      dispatch(changePieData(data))
    })
  }, [dispatch])

  // 引导页flag
  const changeFlag = (flag: boolean) => {
    setshowIntro(flag)
  }
  useEffect(() => {
    if (data?.list) {
      // 右侧图表数据的展示
      const { newList, newList2 } = getPieData(data.list, 'all')
      setListData(newList2)
      // 左侧图表数据的展示
      setDefaultPieData(newList)
      dispatch(changePieData(newList))
      // 总销售额
    }
    if (orderList) {
      // 总销售额
      const total = orderList.reduce((pre: number, cur: Orderlist) => {
        return pre + cur.payAmount
      }, 0)
      setTotalSales(total)

      // 处理订单数据，统计每天的商品数量
      const produceCountObj: Record<string, number> = {}

      orderList.forEach((item: Orderlist) => {
        const data = item.SubmitTime.split(' ')[0]
        const count = item.commodity.length
        if (produceCountObj[data]) {
          produceCountObj[data] += count
        } else {
          produceCountObj[data] = count
        }
      })
      const keyList = Object.keys(produceCountObj)
      const countList = Object.values(produceCountObj)
      setPayDate(keyList)
      setPayCount(countList)
    }
    return
  }, [data, dispatch, orderList])

  if (isError || isError2) return <div>error</div>
  if (isLoading || isLoading2) return <div>loading</div>

  const ChangePieData = (value: string) => {
    setShowStatus(value)
    // 右侧图表数据的展示
    const { newList, newList2 } = getPieData(data.list, value)
    setListData(newList2)
    // 左侧图表数据的展示
    dispatch(changePieData(newList))
  }
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const { accessOption, payOption, pieOption, tradeOption } = useEchartsData(
    payDate,
    payCount,
    defaultPieData
  )

  return (
    <>
      {showIntro && <HomeIntro changeFlag={changeFlag} />}
      <div className="card-container">
        <Card bordered={false} className="card">
          <div>
            <h3>总销售额</h3>
            <h3 className="card-title">￥{totalSales.toFixed(2)}</h3>
            <div className="card-title-box">
              <p>
                <span>
                  周同比 5.67%
                  <CaretUpOutlined style={{ color: 'green' }} />
                </span>
                <span style={{ marginLeft: 40 }}>
                  日同比 19.96%
                  <CaretDownOutlined style={{ color: 'red' }} />
                </span>
              </p>
            </div>
          </div>
          <hr />
          <p>日销售额 ￥12,423</p>
        </Card>
        <Card bordered={false} className="card">
          <div>
            <h3>访问量</h3>
            <h3 className="card-title">￥{`${126},${560}`}</h3>
            <Echarts
              option={accessOption}
              style={{ height: '100px', width: '100%' }}
            />
          </div>
          <hr />
          <p>日访问量 ￥12,423</p>
        </Card>
        <Card bordered={false} className="card">
          <div>
            <h3>支付笔数</h3>
            <h3 className="card-title">￥{`${126},${560}`}</h3>
            <Echarts
              option={payOption}
              style={{ height: '100px', width: '100%' }}
            />
          </div>
          <hr />
          <p>转化率 40.35%</p>
        </Card>
        <Card bordered={false} className="card">
          <div>
            <h3>运营活动效果</h3>
            <h3 className="card-title">123,45</h3>
            <div id="access2">
              <Progress percent={75} strokeColor={'#52C41A'} />
            </div>
          </div>
          <hr />
          <p>日销售额 ￥12,423</p>
        </Card>
      </div>
      <Card
        title={
          <>
            <span>品牌销售额占比</span>
            <Radio.Group
              defaultValue="a"
              buttonStyle="solid"
              style={{ float: 'right' }}
              value={showStatus}
              onChange={(e) => ChangePieData(e.target.value)}
            >
              <Radio.Button value="all">全部</Radio.Button>
              <Radio.Button value="on">线上</Radio.Button>
              <Radio.Button value="off">线下</Radio.Button>
            </Radio.Group>
          </>
        }
        bordered={false}
        className="card"
      >
        <div className="pie-content">
          <Echarts
            option={pieOption}
            style={{ height: '300px', width: '100%' }}
          />
        </div>
        <div className="pie-text">
          <List
            bordered
            dataSource={listData}
            renderItem={(item) => (
              <List.Item>
                <Typography.Text mark></Typography.Text> {item}
              </List.Item>
            )}
          />
        </div>
      </Card>
      <Card className="pay">
        <Echarts
          option={tradeOption}
          style={{ height: '300px', width: '100%' }}
        />
      </Card>
    </>
  )
}

export default App
